const fs = require('fs');
const path = require('path');

/**
 * 音效生成脚本
 * 生成启动系统、操作成功、操作失败三种音效
 */

// 输出目录
const outputDir = path.join(__dirname, '../resources/audio');

// 确保输出目录存在
if (!fs.existsSync(outputDir)) {
  fs.mkdirSync(outputDir, { recursive: true });
}

/**
 * 生成WAV文件头
 */
function generateWAVHeader(dataSize, sampleRate = 44100, channels = 2, bitsPerSample = 16) {
  const buffer = Buffer.alloc(44);
  let offset = 0;

  // RIFF header
  buffer.write('RIFF', offset);
  offset += 4;
  buffer.writeUInt32LE(36 + dataSize, offset);
  offset += 4;
  buffer.write('WAVE', offset);
  offset += 4;

  // fmt chunk
  buffer.write('fmt ', offset);
  offset += 4;
  buffer.writeUInt32LE(16, offset);
  offset += 4; // chunk size
  buffer.writeUInt16LE(1, offset);
  offset += 2; // audio format (PCM)
  buffer.writeUInt16LE(channels, offset);
  offset += 2;
  buffer.writeUInt32LE(sampleRate, offset);
  offset += 4;
  buffer.writeUInt32LE((sampleRate * channels * bitsPerSample) / 8, offset);
  offset += 4;
  buffer.writeUInt16LE((channels * bitsPerSample) / 8, offset);
  offset += 2;
  buffer.writeUInt16LE(bitsPerSample, offset);
  offset += 2;

  // data chunk
  buffer.write('data', offset);
  offset += 4;
  buffer.writeUInt32LE(dataSize, offset);
  offset += 4;

  return buffer;
}

/**
 * 生成音频数据
 */
function generateAudioData(frequencies, duration, sampleRate = 44100, envelope = 'fade') {
  const samples = Math.floor(duration * sampleRate);
  const channels = 2;
  const buffer = Buffer.alloc(samples * channels * 2); // 16-bit samples

  for (let i = 0; i < samples; i++) {
    const time = i / sampleRate;
    let sample = 0;

    // 生成复合音调
    frequencies.forEach((freq, index) => {
      let tone = Math.sin(2 * Math.PI * freq * time);

      // 添加泛音
      tone += 0.3 * Math.sin(2 * Math.PI * freq * 2 * time);
      tone += 0.1 * Math.sin(2 * Math.PI * freq * 3 * time);

      sample += tone * 0.2; // 降低音量避免削波
    });

    // 应用包络
    let envValue = 1;
    switch (envelope) {
      case 'fade':
        envValue = Math.max(0, 1 - time / duration);
        break;
      case 'attack':
        envValue = Math.min(1, time * 10) * Math.max(0, 1 - time / duration);
        break;
      case 'bell':
        envValue = Math.exp(-time * 3) * Math.min(time * 20, 1);
        break;
    }

    const finalSample = Math.max(-1, Math.min(1, sample * envValue));
    const intSample = Math.floor(finalSample * 32767);

    // 写入立体声数据
    buffer.writeInt16LE(intSample, i * 4); // 左声道
    buffer.writeInt16LE(intSample, i * 4 + 2); // 右声道
  }

  return buffer;
}

/**
 * 生成启动音效
 * 优雅的C大调和弦，渐进式播放
 */
function generateStartupSound() {
  console.log('生成启动音效...');

  const frequencies = [261.63, 329.63, 392.0]; // C-E-G和弦
  const duration = 1.5;
  const audioData = generateAudioData(frequencies, duration, 44100, 'bell');
  const header = generateWAVHeader(audioData.length);
  const wavFile = Buffer.concat([header, audioData]);

  const filePath = path.join(outputDir, 'startup.wav');
  fs.writeFileSync(filePath, wavFile);
  console.log(`启动音效已生成: ${filePath}`);
}

/**
 * 生成成功音效
 * 明亮的上行音阶
 */
function generateSuccessSound() {
  console.log('生成成功音效...');

  // 上行音阶：C-E-G-C (高八度)
  const frequencies = [261.63, 329.63, 392.0, 523.25];
  const duration = 0.8;
  const audioData = generateAudioData(frequencies, duration, 44100, 'attack');
  const header = generateWAVHeader(audioData.length);
  const wavFile = Buffer.concat([header, audioData]);

  const filePath = path.join(outputDir, 'success.wav');
  fs.writeFileSync(filePath, wavFile);
  console.log(`成功音效已生成: ${filePath}`);
}

/**
 * 生成失败音效
 * 下行的不和谐音
 */
function generateErrorSound() {
  console.log('生成失败音效...');

  // 下行减七和弦：G-F-D#-C#
  const frequencies = [392.0, 349.23, 311.13, 277.18];
  const duration = 1.0;
  const audioData = generateAudioData(frequencies, duration, 44100, 'fade');
  const header = generateWAVHeader(audioData.length);
  const wavFile = Buffer.concat([header, audioData]);

  const filePath = path.join(outputDir, 'error.wav');
  fs.writeFileSync(filePath, wavFile);
  console.log(`失败音效已生成: ${filePath}`);
}

/**
 * 生成通知音效
 * 简单的提示音
 */
function generateNotificationSound() {
  console.log('生成通知音效...');

  // 简单的两音提示：E-C
  const frequencies = [329.63, 261.63];
  const duration = 0.6;
  const audioData = generateAudioData(frequencies, duration, 44100, 'bell');
  const header = generateWAVHeader(audioData.length);
  const wavFile = Buffer.concat([header, audioData]);

  const filePath = path.join(outputDir, 'notification.wav');
  fs.writeFileSync(filePath, wavFile);
  console.log(`通知音效已生成: ${filePath}`);
}

// 主执行函数
function main() {
  console.log('开始生成音效文件...');
  console.log(`输出目录: ${outputDir}`);

  try {
    generateStartupSound();
    generateSuccessSound();
    generateErrorSound();
    generateNotificationSound();

    console.log('\n✅ 所有音效文件生成完成！');
    console.log('\n生成的文件:');
    console.log('- startup.wav      (启动音效)');
    console.log('- success.wav      (成功音效)');
    console.log('- error.wav        (失败音效)');
    console.log('- notification.wav (通知音效)');
  } catch (error) {
    console.error('❌ 生成音效文件时出错:', error);
    process.exit(1);
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  main();
}

module.exports = {
  generateStartupSound,
  generateSuccessSound,
  generateErrorSound,
  generateNotificationSound
};
